<?php

namespace App\Services;

use App\Models\Crm_Member;
use App\Models\Crm_Order;
use App\Third\Acsign\Acsing;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;

class OrderService
{
    public function orderList($params)
    {
        $result = Crm_Order::getFilter($params)->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $list['list'] = $result->items();
        return $list;
    }
    public function checkOrder($params)
    {
        $order = Crm_Order::where('agencyid',$params['aid'])
            ->where('mid',$params['mid'])
            ->first();
        if(empty($order)){
            return ['code' => 200,'status' => true ,'data' => []];
        }else{
            return ['code' => 1015,'status' => false ,'data' => []];
        }
    }
    public function createOrder($params)
    {

        try {
            // 开始数据库事务
            DB::beginTransaction();
            $order = Crm_Order::create([
                'agencyid' => $params['aid'],
                'ordersn' => Crm_Order::_generateSn('O',$params['aid']),
                'mid' => $params['mid'],
                'realname' => $params['realname'],
                'mobile' => $params['mobile'],
                'idcard' => $params['idcard'],
                'package_name' => $params['package_name'] ?: '自定义套餐',
                'price' => $params['price'],
                'days' => $params['days'],
                'nums' => $params['nums'],
                'signdate' => $params['signdate'],
                'startdate' => $params['startdate'],
                'enddate' => Carbon::parse($params['startdate'])->addDay($params['days'])->toDate(),
                'belongid' => $params['belongid'],
                'serviceid' => $params['serviceid'],
                'inviteid' => $params['inviteid'],
                'remark' => $params['remark']
            ]);
            if(!$order){
                throw new \Exception("创建Crm_Order订单失败");
            }
            $member = Crm_Member::find($params['mid']);
            $member->serviceid = $params['serviceid'];
            if(!$member->save()){
                throw new \Exception("更新Crm_Member服务人失败");
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }


}
